/*
 * @Copyright: Citylife 2021
 * @Author: shaokui.gu
 * @Date: 2020-12-23 13:35:50
 * @Description: /我的/设置
 */
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../base/base.dart';
import '../../base/base_page.dart';
import '../../components/table_view_cell.dart';
import '../../utils/locale/local_manager.dart';
import '../../utils/sizer/sizer_ext.dart';
import '../../utils/toast/toast_manager.dart';

class SettingController extends TemplateController {
  SettingController() : super();

  final mainList = [].obs;

  final List themeList = [
    {
      "title": () => appString.gensuixitong,
    },
    {
      "title": () => appString.qiansemoshi,
    },
    {
      "title": () => appString.shensemoshi,
    }
  ].obs;

  final _cacheSize = '0.00B'.obs;
  get cacheSize => this._cacheSize.value;
  set cacheSize(value) => this._cacheSize.value = value;

  final _darkModeEnabled = theme.isDark.obs;
  bool get darkModeEnabled => this._darkModeEnabled.value;
  set darkModeEnabled(bool value) {
    this._darkModeEnabled.value = value;
    _updateDarkModeEnabled(value);
  }

  @override
  void onInit() async {
    super.onInit();
    _initRightWidgets();
    _loadLocalCache();
    SharedPreferences prefs = await SharedPreferences.getInstance();
    darkModeEnabled = prefs.getBool("dark_mode_enabled") ?? false;
  }

  _initRightWidgets() {
    List list = [
      {
        "title": () => appString.qingchuhuancun,
        "action": clearCache,
        "widget": Obx(() => Text(
              cacheSize,
              style: TextStyle(
                color: theme.colors.switcherOnColor,
                fontSize: 14.0.w,
              ),
            ))
      },
      {
        "title": () => appString.yuyan,
        "action": () {
          Get.toNamed("/languages");
        },
        "widget": Text(
          "\uf054",
          style: TextStyle(
            fontSize: 18.0.sp,
            fontFamily: IconFont,
            color: theme.colors.defaultIconColor,
          ),
        )
      },
      {
        "title": () => appString.shensemoshi,
        "action": null,
        "widget": SizedBox(
          width: 56.0.w,
          child: Obx(
            () => Switch.adaptive(
              value: darkModeEnabled,
              activeColor: theme.colors.switcherOnColor,
              onChanged: (value) => darkModeEnabled = value,
            ),
          ),
        ),
      }
    ];
    mainList.addAll(list);
  }

  _updateDarkModeEnabled(bool enabled) async {
    if (!enabled) {
      theme.themeMode = ThemeMode.light;
    }
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setBool("dark_mode_enabled", enabled);
  }

  /// 计算缓存大小
  _loadLocalCache() async {
    Directory tempDir = await getTemporaryDirectory();
    double value = await _getTotalSizeOfFilesInDir(tempDir);
    cacheSize = _renderSize(value);
  }

  Future<double> _getTotalSizeOfFilesInDir(final FileSystemEntity file) async {
    // 文件不存在，直接返回0
    if (!file.existsSync()) {
      return 0;
    }
    if (file is File) {
      int length = await file.length();
      return double.parse(length.toString());
    }
    if (file is Directory) {
      final List children = file.listSync();
      double total = 0;
      for (final FileSystemEntity child in children)
        total += await _getTotalSizeOfFilesInDir(child);
      return total;
    }
    return 0;
  }

  _renderSize(double value) {
    List<String> unitArr = ['B', 'K', 'M', 'G'];
    int index = 0;
    while (value > 1024) {
      index++;
      value = value / 1024;
    }
    String size = value.toStringAsFixed(2);
    return size + unitArr[index];
  }

  void clearCache() async {
    //此处展示加载loading
    isFetchingData = true;
    try {
      Directory tempDir = await getTemporaryDirectory();
      //删除缓存目录
      await _delDir(tempDir);
      await _loadLocalCache();
    } catch (e) {
      ToastManager.showToast(msg: e.toString());
      print(e);
    } finally {
      //此处隐藏加载loading
      isFetchingData = false;
    }
  }

  /// 递归方式删除目录 清除缓存
  _delDir(FileSystemEntity file) async {
    if (file is Directory) {
      final List<FileSystemEntity> children = file.listSync();
      for (final FileSystemEntity child in children) {
        await _delDir(child);
      }
    }
    PaintingBinding.instance.imageCache.clear();
    PaintingBinding.instance.imageCache.clearLiveImages();
    await file.delete();
  }
}

class SettingPage extends TemplatePage<SettingController> {
  SettingPage() : super(title: appString.shezhi);
  @override
  Widget buildBody(BuildContext context) {
    return Obx(
      () => ListView.builder(
        padding: EdgeInsets.zero,
        physics: NeverScrollableScrollPhysics(),
        shrinkWrap: true,
        itemCount: controller.darkModeEnabled
            ? controller.mainList.length + controller.themeList.length
            : controller.mainList.length,
        itemBuilder: (context, index) {
          Widget rightWidget;
          if (index < controller.themeList.length) {
            rightWidget = controller.mainList[index]["widget"];
          } else {
            rightWidget = Obx(() => (controller.darkModeEnabled &&
                    ThemeMode.values.indexOf(theme.themeMode) ==
                        index - controller.mainList.length)
                ? Text(
                    "\uf058",
                    style: TextStyle(
                      fontSize: 18.0.sp,
                      fontFamily: IconFont,
                      color: theme.colors.defaultIconColor,
                    ),
                  )
                : Container());
          }

          List titleList = []
            ..addAll(controller.mainList)
            ..addAll(controller.themeList);

          String title = titleList[index]["title"]();
          return TableViewCell.defaultCell(
            title: title,
            height: 50.0.w,
            rightWidget: rightWidget,
            onTap: () {
              if (index < controller.mainList.length) {
                if (controller.mainList[index]["action"] != null) {
                  controller.mainList[index]["action"]();
                }
              } else if (index >= controller.mainList.length) {
                theme.themeMode =
                    ThemeMode.values[index - controller.mainList.length];
              }
            },
            // hasLine: (controller.darkModeEnabled && index != 5) ||
            // (!controller.darkModeEnabled && index != 2),
          );
        },
      ),
    );
  }

  @override
  SettingController initController() {
    return SettingController();
  }
}
